package com.eatme.web;

import com.google.common.collect.Maps;
import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ActivitiDemo {
    private static final Logger LOG = LoggerFactory.getLogger(ActivitiDemo.class);
    public static void main(String[] args) throws ParseException {
        LOG.info("启动我们的程序");
        // 创建流程引擎
        ProcessEngine processEngine = getProcessEngine();
        // 部署流程定义文件
        ProcessDefinition processDefinition = getProcessDefinition(processEngine);
        // 启动运行流程
        ProcessInstance processInstance =  getProcessInstance(processEngine, processDefinition);
        // 处理流程任务
        processTask(processEngine, processInstance);
        LOG.info("结束我们的程序");

    }

    private static void processTask(ProcessEngine processEngine, ProcessInstance processInstance) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        while (processInstance !=null&&!processInstance.isEnded()) {
            TaskService taskService = processEngine.getTaskService();
            List<Task> list = taskService.createTaskQuery().list();
            LOG.info("待处理任务数量:[{}]",list.size());
            for(Task task : list) {
                LOG.info("待处理任务id:[{}]",task.getId());
                LOG.info("待处理任务名称:[{}]",task.getName());
                LOG.info("待处理任务assignee:[{}]",task.getAssignee());
                Map<String, Object> variables =  getVariables(scanner, processEngine,task);
                taskService.complete(task.getId(),variables);
                processInstance = processEngine.getRuntimeService()
                        .createProcessInstanceQuery()
                        .processDefinitionId(processInstance.getId()).singleResult();
            }
        }
        scanner.close();
    }

    private static Map<String, Object> getVariables(Scanner scanner, ProcessEngine processEngine, Task task) throws ParseException {
        UserTask userTask =(UserTask)processEngine.getRepositoryService().getBpmnModel(task.getProcessDefinitionId()).getFlowElement(task.getTaskDefinitionKey());
        List<FormProperty> formProperties = userTask.getFormProperties();
        Map<String,Object> variables = Maps.newHashMap();
        for(FormProperty formProperty: formProperties) {
            String line = null;
            if (formProperty.getType().equals("string")) {
                LOG.info("请输入 {} ?",formProperty.getName());
                line = scanner.nextLine();
                variables.put(formProperty.getId(),line);
            }else if (formProperty.getType().equals("date")){
                LOG.info("请输入 {} ?格式 (yyyy-MM-dd)",formProperty.getName());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                line = scanner.nextLine();
                Date date = simpleDateFormat.parse(line);
                variables.put(formProperty.getId(),date);
            }else if (formProperty.getType().equals("boolean")) {
                LOG.info("请输入 {} ?",formProperty.getName());
                line = scanner.nextLine();
                if (line.equals("true")) {
                    variables.put(formProperty.getId(),true);
                }else {
                    variables.put(formProperty.getId(),false);
                }

            }else {
                LOG.info("类型暂不支持 {} ?",formProperty.getType());
            }
            LOG.info("你输入的内容是 [{}]",line);

        }
        return variables;
    }

    private static ProcessInstance getProcessInstance(ProcessEngine processEngine, ProcessDefinition processDefinition) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        LOG.info("启动流程:[{}]",processInstance.getProcessDefinitionKey());
        return processInstance;
    }

    private static ProcessDefinition getProcessDefinition(ProcessEngine processEngine) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addClasspathResource("second_approve.bpmn");
        Deployment deployment = deploymentBuilder.deploy();
        String deploymentId = deployment.getId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        LOG.info("流程定义文件:[{}],流程ID:[{}]",processDefinition.getName(),processDefinition.getId());
        return processDefinition;
    }

    private static ProcessEngine getProcessEngine() {
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String name = processEngine.getName();
        LOG.info("流程引擎名称:[{}]",name);
        return processEngine;
    }
}
